package com.tgy.leetcode;

/**
 * @Author: tgy
 * @Date: 1/13/21 9:54 AM
 *
 *  https://leetcode-cn.com/problems/merge-k-sorted-lists/
 *
 */
public class _23_合并K个升序链表 {

    public ListNode mergeKLists(ListNode[] lists) {

//        dummy

        if (lists == null || lists.length == 0) {

            return null;
        }

        if (lists.length == 1) {
            return lists[0];
        }

        ListNode head = merge(lists[0],lists[1]);

        for (int i = 2; i < lists.length; i++) {

            head = merge(head,lists[i]);
        }

        return head;
    }

    private ListNode merge(ListNode head1, ListNode head2) {

        ListNode dummyHead = new ListNode();
        ListNode tail = dummyHead;

        while (head1 != null) {

            if (head2 != null && head1.val >= head2.val) {

                tail.next = head2;
                head2 = head2.next;
                tail = tail.next;
            }else {

                tail.next = head1;
                head1 = head1.next;
                tail = tail.next;
            }
        }

        if (head2 != null) {

            tail.next = head2;
        }

        return dummyHead.next;
    }
}
